import { useState, useEffect } from 'react'

export default class MyLoader {
  _resultTips: string
  _timer?: number
  _loading: boolean
  _setTips: (msg: string, time?: number) => void
  _operationFunc: <T>(operation: () => Promise<T>) => Promise<T>

  constructor() {
    const [loading, setLoading] = useState<boolean>(false)
    const [resultTips, setResultTips] = useState<string>('')
    const [timer, setTimer] = useState<number | undefined>(undefined)

    this._resultTips = resultTips
    this._timer = timer
    this._loading = loading

    useEffect(() => {
      return () => {
        if (timer) clearTimeout(timer)
      }
    }, [timer])

    this._setTips = (msg: string, time: number = 3600): void => {
      if (timer) clearTimeout(timer)

      setResultTips(msg)

      setTimer(
        setTimeout(() => {
          setResultTips('')
        }, time) as unknown as number
      )
    }

    this._operationFunc = async <T>(func: () => Promise<T>): Promise<T> => {
      try {
        setLoading(true)
        const result = await func()
        return result
      } finally {
        setLoading(false)
      }
    }
  }
}
